package com.panshi.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.panshi.auth.JWT;
import com.panshi.interceptor.GlobalInterceptor;
import com.panshi.interceptor.LoginInterceptor;
import com.panshi.model.UcenterMember;
import com.panshi.tools.IPUtils;
import com.panshi.tools.MyTimeTools;
import com.panshi.tools.ResponseData;
import com.panshi.tools.StringTools;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.List;

public class MemberController extends Controller {


    public void auth() {

        String name = getPara("name");
        String password = getPara("password");

        // 验证用户名密码非空
        if (StringTools.isEmptyString(name) || StringTools.isEmptyString(password)) {
            renderJson(ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, "用户名密码不能为空"));
            return;
        }
        String md5Hex = DigestUtils.md5Hex(DigestUtils.sha1Hex(password) + PropKit.get("PASSWORD_KEY"));

        if (name.equals("tony") && password.equals("abc123")) {
            UcenterMember m = new UcenterMember();
            m.setUsername("tony");
            m.setPassword("abc123");
            String token = JWT.sign(m, 30L * 24L * 3600L * 1000L);//毫秒级别,30天*24小时*3600秒*1000L
//            String token = JWT.sign(m, 1000L*60L);
            if (token != null) {
                setAttr("token", token);
            }
        }
        renderJson();
    }

    @Before(LoginInterceptor.class)
    public void authtest() {
        UcenterMember ucentermember = getAttr("ucentermember");
        renderText(ucentermember.getUsername());
    }




    /**
     * 用户注册接口
     */


    @ActionKey("/register")
    @Before({GlobalInterceptor.class, Tx.class})
    public void register() {

        String mobile = getPara("mobile"); //手机号码
        String shortMessage = getPara("shortMessage");//短信验证码
        String password = getPara("password");//密码


        // 验证手机验证码
        SMSController smsController = new SMSController();
        boolean shortMessageCheck = smsController.short_message_check(mobile, shortMessage);
        if (!shortMessageCheck) {
            renderJson(ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, "短信验证码验证失败"));
            return;
        }
        //TODO 检查渠道黑名单

        // 检查用户是否注册

        if (checkMemberExist(mobile)) {
            renderJson(ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, "该用户已经注册"));
            return;
        }
        // 注册账号
        Record member = new Record();
        String password_md5 = DigestUtils.md5Hex(DigestUtils.sha1Hex(password) + PropKit.get("PASSWORD_KEY"));//密码加密
        Long reg_ip = IPUtils.getIpToLong(IPUtils.getIpAddr(getRequest()));//获取客户端IP
        member.set("username", mobile).set("password", password_md5).set("mobile", mobile).set("reg_time", MyTimeTools.getUnixTimeMills())
                .set("reg_ip", reg_ip).set("status", 0).set("pay_rules", 0).set("packageId", getAttr("packageId"));
        Db.save("ot_app_member", member);
        //TODO 生成MT4账号
        Record task = new Record();
        task.set("task_name", "user_info_add").set("task_desc", "为用户" + mobile + "补充信息").set("task_create_time", MyTimeTools.getUnixTimeMills());
        Db.save("ot_app_task", task);

        renderJson(ResponseData.ok());
    }


    /**
     * 检查用户是否存在
     */

    public boolean checkMemberExist(String mobile) {
        List<Record> users = Db.find("select *  from ot_app_member  where username='" + mobile + "'");
        return users.size() > 0 ? true : false;
    }


    /**
     * 检查用户是否在黑名单中
     *
     * @return
     */
    private boolean checkMemberBlacklist(String packageId) {
        List<Record> records = Db.find("select *  from ot_app_market_blacklist where market=" + packageId);
        return records.size() > 0 ? true : false;
    }


}
